import React, { useEffect, useRef, useState } from "react";
import service from "@/http/request";
import { Button } from "antd";

import { useDispatch } from "react-redux";
import { CaretUpOutlined } from "@ant-design/icons";

import { setHasLuckyFrame } from "@/store/userSlice";

const DrawPrizes = () => {
  const canvasRef = useRef(null);
  const [isSpinning, setIsSpinning] = useState(false);
  const [angle, setAngle] = useState(0);
  const [selectedPrize, setSelectedPrize] = useState(null);
  const [lottery, setLottery] = useState(0);
  const prizes = [
    "积分+20",
    "积分+100",
    "积分+200",
    "欧皇称号",
    "幸运头像框",
    "谢谢参与",
  ];

  const con = {
    POINTS_20: "积分+20",
    POINTS_100: "积分+100",
    POINTS_200: "积分+200",
    TITLE_LUCKY: "欧皇称号",
    FRAME_LUCKY: "幸运头像框",
    NONE: "谢谢参与",
  };

  //   POINTS_20("积分+20", "POINTS", "20"),
  // POINTS_100("积分+100", "POINTS", "100"),
  // POINTS_200("积分+200", "POINTS", "200"),
  // TITLE_LUCKY("欧皇称号", "USER_TITLE", "欧皇"),         // ✅ 修改
  // FRAME_LUCKY("幸运头像框", "AVATAR_FRAME", "lucky_frame"), // ✅ 修改
  // NONE("谢谢参与", "NONE", null);

  const drawWheel = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const size = 400;
    const radius = size / 2;
    canvas.width = size;
    canvas.height = size;
    ctx.clearRect(0, 0, size, size);

    const arc = (2 * Math.PI) / prizes.length;

    prizes.forEach((prize, i) => {
      const startAngle = arc * i + angle;
      const endAngle = startAngle + arc;

      ctx.beginPath();
      ctx.moveTo(radius, radius);
      ctx.fillStyle = i % 2 === 0 ? "#FFA500" : "#FF69B4";
      ctx.arc(radius, radius, radius, startAngle, endAngle, false);
      ctx.fill();

      ctx.save();
      ctx.fillStyle = "#fff";
      ctx.translate(
        radius + Math.cos(startAngle + arc / 2) * radius * 0.7,
        radius + Math.sin(startAngle + arc / 2) * radius * 0.7
      );
      ctx.rotate(startAngle + arc / 2 + Math.PI / 2);
      ctx.font = "14px sans-serif";
      ctx.fillText(prize, -ctx.measureText(prize).width / 2, 0);
      ctx.restore();
    });

    // 中心按钮
    ctx.beginPath();
    ctx.fillStyle = "#FF8C00";
    ctx.arc(radius, radius, 50, 0, 2 * Math.PI);
    ctx.fill();
    ctx.fillStyle = "#fff";
    ctx.font = "18px bold sans-serif";
    ctx.fillText("50/次", radius - 20, radius + 6);
  };

  useEffect(() => {
    drawWheel();
    getLottery();
  }, [angle]);

  const spinToPrize = (prizeName) => {
    const prizeIndex = prizes.findIndex((p) => p === prizeName);
    if (prizeIndex === -1) return;

    const arc = (2 * Math.PI) / prizes.length;
    const targetAngle =
      2 * Math.PI * 5 +
      (2 * Math.PI - (arc * prizeIndex + arc / 2)) +
      Math.PI / 2;

    const duration = 3000;
    const start = Date.now();

    const animate = () => {
      const now = Date.now();
      const elapsed = now - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setAngle(targetAngle * eased);

      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        setSelectedPrize(prizeName);
        if (prizeName === "幸运头像框") {
          dispatch(setHasLuckyFrame(true));
        }
        setIsSpinning(false);
      }
    };

    animate();
  };

  const handleDraw = async () => {
    if (isSpinning) return;
    setIsSpinning(true);
    setSelectedPrize(null);

    try {
      const res = await service.post("/points/lottery");
      console.log(res);

      const prize = con[res];
      // const prize = '欧皇'

      // const prize = res?.name || "谢谢参与";
      spinToPrize(prize);
    } catch (error) {
      console.error("抽奖失败：", error);
      setIsSpinning(false);
    }
  };

  const getLottery = async () => {
    const res = await service.get("/points/lottery/remaining");
    setLottery(res);
  };

  const dispatch = useDispatch();

  return (
    <div
      className="draw-wrapper"
      style={{ textAlign: "center", marginTop: "30px", position: "relative" }}
    >
      <h2>积分抽奖</h2>
      <p style={{ fontSize: "18px" }}>我的积分：{lottery}</p>

      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <canvas
          ref={canvasRef}
          style={{
            borderRadius: "50%",
            margin: "20px 0",
            zIndex: 1,
            width: "500px",
          }}
        />
        <div>
          <CaretUpOutlined />
        </div>
        <Button
          onClick={handleDraw}
          disabled={isSpinning}
          style={{ padding: "10px 30px", fontSize: "16px" }}
        >
          {isSpinning ? "抽奖中..." : "开始"}
        </Button>
      </div>
      {selectedPrize && (
        <p style={{ marginTop: "20px", fontSize: "18px", color: "green" }}>
          🎉 恭喜你获得：<strong>{selectedPrize}</strong>
        </p>
      )}
    </div>
  );
};

export default DrawPrizes;
